#include "extEEPROM.h"

#define DATAOUT 11//MOSI
#define DATAIN  12//MISO 
#define SPICLOCK  13//sck
int slaveSelectPin = 10;

//opcodes
#define WREN  6
#define WRDI  4
#define RDSR  5
#define WRSR  1
#define READ  3
#define WRITE 2


extEEPROM::extEEPROM()
{
	SPI.begin();
	SPI.setBitOrder(MSBFIRST);
	SPI.setClockDivider(SPI_CLOCK_DIV4);
	SPI.setDataMode(SPI_MODE0);
	SPI.detachInterrupt();
}


uint8_t extEEPROM::readByte(int EEPROM_address)
{
  //READ EEPROM
  uint8_t data;
  digitalWrite(slaveSelectPin, LOW);
  SPI.transfer(READ); //transmit read opcode
  SPI.transfer((uint8_t)(EEPROM_address>>8));   //send MSByte address first
  SPI.transfer((uint8_t)(EEPROM_address));      //send LSByte address
  data = SPI.transfer(0xFF); //get data byte
  //add code to check status of chip before going on to more reads
  digitalWrite(slaveSelectPin, HIGH); //release chip, signal end transfer
  return data;
}


void extEEPROM::writeByte(int address, uint8_t value){
	digitalWrite(slaveSelectPin,LOW);
	SPI.transfer(WREN);
  	digitalWrite(slaveSelectPin, HIGH);
	delay(10);
	digitalWrite(slaveSelectPin,LOW);

	SPI.transfer(WRITE); //write instruction
	SPI.transfer((uint8_t)(address>>8));   //send MSByte address first
	SPI.transfer((uint8_t)(address));      //send LSByte address
	SPI.transfer(value); //write data byte

	//block write protection level?  
	//add code to check status of chip before going on to more writes
	digitalWrite(slaveSelectPin,HIGH); //release chip
}

void extEEPROM::writeBuff(int address, uint8_t* buff2Write, size_t nBuffBytes){
  digitalWrite(slaveSelectPin,LOW);
  SPI.transfer(WREN);
  	digitalWrite(slaveSelectPin, HIGH);
	delay(10);
	digitalWrite(slaveSelectPin,LOW);

  SPI.transfer(WRITE); //write instruction
  SPI.transfer((uint8_t)(address>>8));   //send MSByte address first
  SPI.transfer((uint8_t)(address));      //send LSByte address
  int i;
  for(i=0; i<nBuffBytes; i++){
	SPI.transfer(buff2Write[i]); //write data byte
  }
	//block write protection level?  
	//add code to check status of chip before going on to more writes
  digitalWrite(slaveSelectPin,HIGH); //release chip
}